import os
import re

# 获取当前目录下的所有.f90和.f03文件
fortran_files = [f for f in os.listdir('.') if re.match(r'.*\.(f90|f03)$', f)]
# fortran_files = ['moddata.f90', 'module3.f90', 'example.f90', 'foo.f90', 'module2.f90', 'module1.f90' ]
# 假设模块名称与文件名相同，但不包括扩展名
modules = [os.path.splitext(f)[0] for f in fortran_files]

# 生成依赖关系映射
dependencies = {module: [] for module in modules}

# 解析文件并填充dependencies字典
def parse_dependencies():
    for file in fortran_files:
        module_name = os.path.splitext(file)[0]
        with open(file, 'r') as f:
            content = f.read()
            # 查找模块依赖项
            for mod in modules:
                if re.search(r'\buse ' + mod + r'\b', content, re.IGNORECASE):
                    dependencies[module_name].append(mod)

parse_dependencies()

# 排序模块以满足依赖关系
def sort_modules(dependencies):
    sorted_modules = []
    while dependencies:
        # 找到没有依赖或其依赖已经解决的模块
        independent = [m for m, deps in dependencies.items() if not deps or all(d in sorted_modules for d in deps)]
        if not independent:
            raise Exception('Circular dependency detected!')
        sorted_modules.extend(independent)
        # 移除已经添加的模块
        for m in independent:
            del dependencies[m]
    return sorted_modules

# 输出模块列表
sorted_modules = sort_modules(dependencies)
print(' '.join(sorted_modules))
